<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.name"
        clearable
        class="filter-item"
        style="width: 200px"
        placeholder="请输入名称"
      />
      <el-button
        v-permission="['GET /admin/standardCharges/list']"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >查找
      </el-button>
      <el-button
        v-permission="['POST /admin/standardCharges/create']"
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >添加
      </el-button>
    </div>

    <!-- 查询结果 -->
    <el-table
      :header-cell-style="{background:'#f5f5f5',color:'#333333',height:'50px'}"
      v-loading="listLoading"
      :data="list"
      element-loading-text="正在查询中..."
      border
      fit
      highlight-current-row
    >
      <el-table-column
        width="140"
        align="center"
        label="ID"
        prop="id"
        sortable
      />

      <el-table-column align="center" label="标题" prop="name" width="200"/>

      <el-table-column align="center" label="副标题" prop="subTitle" width="200"/>
      <el-table-column align="center" label="链接地址" prop="url">
        <template slot-scope="scope">
          <el-link :href="scope.row.url" target="_blank">{{scope.row.url}}</el-link>
        </template>

      </el-table-column>
      <el-table-column align="center" label="排序" prop="sortIndex" width="200"/>


      <el-table-column
        align="center"
        label="操作"
        width="260"
        fixed="right"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">

          <el-button
            type="success"
            size="mini"
            v-if="scope.row.isCalculate"
            @click="calculateFun(scope.row)"
          >公式
          </el-button>

          <el-button
            v-permission="['POST /admin/standardCharges/update']"
            type="primary"
            size="mini"
            @click="handleUpdate(scope.row)"
          >编辑
          </el-button>

          <el-button
            v-permission="['GET /admin/standardCharges/delete']"
            type="danger"
            size="mini"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="1200px">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="dataForm"
        status-icon
        label-position="left"
        label-width="140px"
        style="width: 100%; padding-left: 50px;padding-right: 50px;"
      >
        <el-form-item label="标题" prop="name">
          <el-input v-model="dataForm.name" style="width: 80%"/>
        </el-form-item>

        <el-form-item label="副标题" prop="subTitle">
          <el-input v-model="dataForm.subTitle" style="width: 80%"/>
        </el-form-item>

        <el-form-item label="排序" prop="sortIndex">
          <el-input-number v-model="dataForm.sortIndex" :min="1" :max="100000" :step="10" label="排序"></el-input-number>
        </el-form-item>

        <el-form-item label="计算方式" prop="isCalculate">
          <el-switch v-model="dataForm.isCalculate" :active-value="true"
                     :inactive-value="false"
                     active-text="公式"
                     inactive-text="页面url"/>
        </el-form-item>

        <el-form-item label="链接地址" prop="url" v-if="!dataForm.isCalculate">
          <el-input v-model="dataForm.url"/>
        </el-form-item>

        <el-form-item label="单收费标准" prop="isSingle">
          <el-switch v-model="dataForm.isSingle" :active-value="true"
                     :inactive-value="false"
                     active-text="是"
                     inactive-text="否"/>
        </el-form-item>

        <el-form-item label="广告" prop="adIds">
          <el-select v-model="dataForm.adIds" multiple placeholder="请选择" style="width: 80%">
            <el-option
              v-for="item in adList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="服务详情" prop="detail">
          <editor v-model="dataForm.detail" :init="editorInit"/>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button
          v-if="dialogStatus == 'create'"
          type="primary"
          @click="createData"
        >确定
        </el-button>
        <el-button
          v-else
          type="primary"
          :loading="saveLoading"
          @click="updateData"
        >确定
        </el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<style>
</style>

<script>
  import {
    linkList,
    linkDelete,
    linkCreate,
    linkUpdate
  } from '../../api/standardCharges'
  import { createStorage } from '../../api/storage'
  import { listPosition } from '../../api/ad'
  import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
  import Editor from '@tinymce/tinymce-vue'

  export default {
    name: 'StandardCharges',
    components: { Pagination, Editor },
    data() {
      return {
        adList: [],//广告
        list: [],
        total: 0,
        listLoading: true,
        listQuery: {
          page: 1,
          name: undefined,
          sort: '',
          order: '',
          limit: 20
        },
        dataForm: {
          id: undefined,
          name: '',
          subTitle: '',
          sortIndex: 100,
          url: '',
          isCalculate: false,
          isSingle: false,
          adIds: []
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '创建'
        },
        saveLoading: false,
        rules: {
          name: [{ required: true, message: '不能为空', trigger: 'blur' }],
          //url: [{ required: true, message: '不能为空', trigger: 'blur' }],
          sortIndex: [{ required: true, message: '不能为空', trigger: 'blur' }]

        },
        editorInit: {
          language: 'zh_CN',
          height: '400px',
          convert_urls: false,
          plugins: [
            'advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount'
          ],
          toolbar: [
            'searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample ',
            'hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor  fontsizeselect fontselect  backcolor fullscreen'
          ],
          images_upload_handler: function(blobInfo, success, failure) {
            const formData = new FormData()
            formData.append('file', blobInfo.blob())
            createStorage(formData)
              .then(res => {
                success(res.data.data.url)
              })
              .catch(err => {
                console.log(err.data.errmsg)
                failure(err.data.errmsg)
              })
          }
        }
      }
    },
    computed: {},
    created() {
      this.getAdList()
      this.getList()
    },
    methods: {
      getAdList() {
        let that = this
        listPosition({
          position: 2//收费页面广告
        }).then(res => {
          that.adList = res.data.data
        })
      },
      getList() {
        this.listLoading = true
        linkList(this.listQuery)
          .then((response) => {
            this.list = response.data.data.list
            this.total = response.data.data.total
            this.listLoading = false
          })
          .catch(() => {
            this.list = []
            this.total = 0
            this.listLoading = false
          })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      resetForm() {
        this.dataForm = {
          id: undefined,
          name: '',
          subTitle: '',
          sortIndex: 100,
          url: '',
          isCalculate: false,
          isSingle: false,
          detail: '',
          adIds: []

        }
      },
      handleCreate() {
        this.resetForm()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        let that = this
        console.log(this.dataForm)
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            that.saveLoading = true
            linkCreate(this.dataForm)
              .then((response) => {
                that.saveLoading = false
                that.getList()
                this.dialogFormVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '添加成功'
                })
              })
              .catch((response) => {
                that.saveLoading = false
                this.$notify.error({
                  title: '失败',
                  message: response.data.errmsg
                })
              })
          }
        })
      },
      handleUpdate(row) {
        this.dataForm = Object.assign({}, row)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        console.log(this.dataForm)
        let that = this
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            that.saveLoading = true
            linkUpdate(this.dataForm)
              .then(() => {
                that.saveLoading = false
                that.getList()
                this.dialogFormVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '更新成功'
                })
              })
              .catch((response) => {
                that.saveLoading = false
                this.$notify.error({
                  title: '失败',
                  message: response.data.errmsg
                })
              })
          }
        })
      },
      handleDelete(row) {
        linkDelete(row.id)
          .then((response) => {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            this.getList()
          })
          .catch((response) => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
      },
      //计算公式
      calculateFun(row) {
        this.$router.push({
          path: '/links/Calculate',
          query: { chargeId: row.id }
        })
      }
    }
  }
</script>
